package com.sharding.demo.config;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.infra.hint.HintManager;
import org.apache.shardingsphere.sharding.api.sharding.hint.HintShardingAlgorithm;
import org.apache.shardingsphere.sharding.api.sharding.hint.HintShardingValue;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @Author hu xu hong
 * @Date 2023/1/18 16:04
 * ShardingSphere hit分片式路由算法
 */
//@Component
@Slf4j
public class CloudHintShardingAlgorithm implements HintShardingAlgorithm<String> {

    public CloudHintShardingAlgorithm(){
    }

    List<String> tcloudIds = Lists.newArrayList();
    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, HintShardingValue<String> shardingValue) {
        List<String> result = Lists.newArrayList();
   /*     Random random = new Random();
        Integer t =  random.nextInt(10);
        if(t%2 == 0){
            result.add("sharding0");
        }else{
            result.add("sharding1");
        }*/
        result.add("sharding1");
        return result;
    }



    /**
     * @Author shtdhr
     * @Description  Hint方式设置路由规则
     * @Date 2021/8/23 0023 下午 5:39
     * @Param  hintManager
     * @Param  TYPE 分片类型 DATABASE_TABLES 分库分表，DATABASE_ONLY 只分库
     * @Param  tableName 分片表（需要分表的表名）
     * @Param  value 分片值 orgNo (具体看自己需求)
     * @return
     */
    public static void setHintValue(final HintManager hintManager, HintType TYPE, String tableName, String value) {
        switch (TYPE) {
            case DATABASE_TABLES:
                hintManager.addDatabaseShardingValue(tableName, value);
                hintManager.addTableShardingValue(tableName, value);
                return;
            case DATABASE:
                hintManager.addDatabaseShardingValue(tableName, value);
                return;
            case TABLES:
                hintManager.addTableShardingValue(tableName, value);
                return;
            case DATABASE_ONLY:
                hintManager.setDatabaseShardingValue(value);
                return;
            default:
                throw new UnsupportedOperationException("unsupported type");
        }
    }


    @Override
    public Properties getProps() {
        return null;
    }

    @Override
    public void init(Properties properties) {

    }
}
